﻿using System;
using System.Collections.Generic;
using Orange.Logistics.Models;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Entity;

namespace Orange.Logistics.Services {

    public interface IBaseService<T> where T : class {
        //IQueryable<T> GetGrid(string tableName, int pageNo, int pageSize, string where, string sort, bool asc, out int count);
        IQueryable<T> List(Func<T, bool> filter);
        T Find(params object[] keys);
        void Add(T model);
        void Update(T model);
        void Delete(T model);
        void Dispose();
        void SaveChanges();
    }

    public abstract class BaseService<T> : IBaseService<T> where T : class {
        protected LogisticsContext db = new LogisticsContext();

        public IQueryable<T> GetGrid(string tableName, int pageNo, int pageSize, string where, string sortBy, bool isAsc, out int count) {
            string sql = "select * from " + tableName;
            count = db.Set<T>().AsQueryable().Count();
            return db.Set<T>().Skip((pageNo - 1) * pageSize).Take(pageSize);
        }

        public IQueryable<T> List(Func<T, bool> filter) {
            if (filter == null) {
                return db.Set<T>();
            }
            return db.Set<T>().Where(filter).AsQueryable();
        }

        public void Add(T model) {
            db.Set<T>().Add(model);
        }

        public void Delete(T model) {
            db.Entry(model).State = System.Data.EntityState.Deleted;
        }

        public void Update(T model) {
            db.Entry(model).State = System.Data.EntityState.Modified;
        }

        public T Find(params object[] keys) {
            return db.Set<T>().Find(keys);
        }

        public void SaveChanges() {
            db.SaveChanges();
        }

        public void Dispose() {
            db.Dispose();
        }
    }
}
